/* Copyright 2008 Shawn C. Dodd

This file is part of TagFC.  TagFC is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

TagFC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with TagFC.  If not, see <http://www.gnu.org/licenses/>. */

class AccountService {

    boolean transactional = true

    def currentPeriod() {
	// returns a string identifying the current hour suitable for hourly timesheets
	// example: 2008032112
	String.format('%tY%<tm%<td%<tH', new Date())
    }

    def invoiceSummarized( nickname, period, seen, completed ) {
	// Update invoice for Farm/Employer on behalf of Farmer (with no detail -- summaries only)
	//

	// create if doesn't yet exist
	def nick = Nickname.findByDisplayName(nickname)
	def sheet = Timesheet.findByPeriodAndNickname(period, nick)
	if( !sheet ) {
		sheet = new Timesheet()
		sheet.period = period
		sheet.nickname = nick
		sheet.totalSeen = 0
		sheet.totalCompleted = 0
		sheet.paid = false
	}

	// update totals
	sheet.totalSeen = sheet.totalSeen + seen
	sheet.totalCompleted = sheet.totalCompleted + completed

	// and save
	def saved = sheet.save()
	if(!saved) sheet.errors.allErrors.each { log.error "Problem updating invoice: $it" }
    }

    // TODO  def invoiceDetailed()	// includes individual Pieces

    def summarizeUnpaid( nickname ) {
	def nick = Nickname.findByDisplayName(nickname)
	//Timesheet.executeQuery( "select sum(totalCompleted) where nickname = :nickname and paid = false", [nickname:nick] ) // TODO  Err, why doesn't this query work?
	def sheets = Timesheet.findAllByNicknameAndPaid(nick, Boolean.FALSE)
	int c = 0
	for( i in sheets ) c += i.totalCompleted
	return c
    }

    def markAllAsPaid( nickname ) {
	// TODO  use a SQL query instead of pulling everything into memory
	def nick = Nickname.findByDisplayName(nickname)
	def sheets = Timesheet.findAllByNicknameAndPaid(nick, Boolean.FALSE)
	int c = 0
	for( i in sheets ) {
		i.paid = true
		c += i.totalCompleted
	}
	return c
    }
}
